{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import paddle\n",
    "from paddle.nn import Linear\n",
    "import paddle.nn.functional as F\n",
    "import os\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 432x288 with 0 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAJIAAACcCAYAAACUcfL+AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMi4zLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvIxREBQAACmJJREFUeJztnW2MVNUZx39/FnYF5bWLDayENawSaROBrLWGRhHkRVMkfGiCGKjEpqQBsSkEoSSFNCa12rQJL0lrLaFKpbEoKo0NAQMfiC1hNxBcCitgAbe8hyIWmwr09MNctvfcwu7szJk7MzvPL5nM+d9z595ndv8597n33HmunHMYRr70KHYARvfAjGQEwYxkBMGMZATBjGQEwYxkBKGijSTpgKTxxY6jOyC7jmSEoKJHJCMcFW0kScckPSJppaQ/SNog6TNJH0q6W9IySWclfSJpcuxzcyUdjNb9WNK8xHaXSDol6aSk70hykhqivhpJP5N0QtIZSb+U1Dvt7x6aijZSgmnAa8BAYC+wlczfpw74MfCr2LpngW8C/YC5wC8kjQWQNBX4AfAI0AA8lNjPT4G7gdFRfx3wo4J8ozRxzlXsCzhG5h++EtgWWz4N+CdQFem+gAMG3GQ7bwPPRu11wE9ifQ3RZxsAAZeBEbH+B4C/Fftvke+rZwpeLRfOxNr/As47567FNMBtwEVJjwIryIwsPYA+wIfROkOBpti2Pom1B0frNku6vkxAVaDvUDTMSF1EUg3wJjAHeMc5d0XS22QMAXAKuCP2kWGx9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c8nXxM1r59+zydLOXXVcaNG9feTv7Wf8qUKZ7u3bt3XvsqB2xEMoJgRjKCYEYyglBWOdLu3bvb2y+++KLXl7wvuq2tLa999enTx9PJx7fH58eSj2evRGxEMoJgRjKCUFaHts2bN9+wnQ3Jn/hMmzbN01VVVZ5evHixp5PV/Q0fG5GMIJiRjCCYkYwgWFkbo0OsrI2RKmYkIwhmJCMIZiQjCGYkIwhmJCMIZiQjCGYkIwhmJCMIZiQjCGYkIwipzrVJOgccB2qB86ntuGuUamzFimu4c67Tog2pGql9p1JTNhOBxaBUYyvVuK5jhzYjCGYkIwjFMtLLRdpvNpRqbKUaF1CkHMnoftihzQhCqkaSNFVSq6QjkopaTlnSOklnJbXElpVE7fByrG2empEkVQFrgUeBUcATUb3uYrEemJpYViq1w8uvtrlzLpUX8ACwNaaXAcvS2v9NYqoHWmK6FRgStYcArcWMLxbXO8CkUo3POZfqoa0O+CSm26JlpUTJ1Q4vl9rmaRrpRnUo7ZSxA3KtbV4M0jRSGzAspu8ATqa4/2zIqnZ4GuRT27wYpGmkPcBdku6UVA3MJFOru5S4Xjscilg7PIva5lBqtc1TThofAz4CjgLLi5zAbiTzsJ4rZEbLp4EvkTkbOhy9DypSbN8gc9jfD+yLXo+VSnw3etmVbSMIdmXbCIIZyQiCGckIghnJCIIZyQiCGckIghnJCIIZyQjCfwGaN0JV33lHywAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<Figure size 144x144 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "图像数据形状和对应数据为: (28, 28)\n",
      "图像标签形状和对应数据为: (1,) [5]\n",
      "\n",
      "输出第一个批次的第一个图像,对应标签数字为[5]\n"
     ]
    }
   ],
   "source": [
    "import paddle\n",
    "import numpy as np\n",
    "train_dataset=paddle.vision.datasets.MNIST(mode='train')\n",
    "train_data0=np.array(train_dataset[0][0])\n",
    "train_label_0=np.array(train_dataset[0][1])\n",
    "import matplotlib.pyplot as plt\n",
    "plt.figure(\"image\")\n",
    "plt.figure(figsize=(2,2))\n",
    "plt.imshow(train_data0,cmap=plt.cm.binary)\n",
    "plt.axis('on')\n",
    "plt.title('image')\n",
    "plt.show()\n",
    "print('图像数据形状和对应数据为:',train_data0.shape)\n",
    "print('图像标签形状和对应数据为:',train_label_0.shape,train_label_0)\n",
    "print('\\n输出第一个批次的第一个图像,对应标签数字为{}'.format(train_label_0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "class MNIST(paddle.nn.Layer):\n",
    "    def __int__(self):\n",
    "        super(MNIST,self).__init__()\n",
    "        self.fc1=Linear(in_featuress=784,out_features=100)\n",
    "        self.fc2=Linear(in_featuress=100,out_features=100)\n",
    "        self.fc3=Linear(in_featuress=100,out_features=10)\n",
    "    def forward(self,inputs):\n",
    "        outputs1=self.fc1(inputs)\n",
    "        outputs1 = F.ReLU(outputs1)\n",
    "        outputs2=self.fc2(outputs1)\n",
    "        outputs2=F.ReLU(outputs2)\n",
    "        outputs_final=selt.fc3(outputs2)\n",
    "        outputs_final=F.softmax(outputs_final)\n",
    "        return outputs_final"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def norm_img(img):\n",
    "    assert len(img.shape)==3\n",
    "    batch_size,img_h,img_w=img.shape[0],img.shape[1],img.shape[2]\n",
    "    img = img/255\n",
    "    img=paddle.reshape(img,[batch_size,img_h*img_w])\n",
    "    return img"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'MNIST' object has no attribute 'fc1'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-5-ce26d464b56c>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m     21\u001b[0m             \u001b[0mopt\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mstep\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     22\u001b[0m             \u001b[0mopt\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mclear_grad\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 23\u001b[1;33m \u001b[0mtrain\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmodel\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     24\u001b[0m \u001b[0mpaddle\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msave\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmodel\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mstate_dict\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'./mnist.pdparams'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32m<ipython-input-5-ce26d464b56c>\u001b[0m in \u001b[0;36mtrain\u001b[1;34m(model)\u001b[0m\n\u001b[0;32m     13\u001b[0m             \u001b[0mimages\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mnorm_img\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mastype\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'float32'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     14\u001b[0m             \u001b[0mlabels\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mdata\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mastype\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'int64'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 15\u001b[1;33m             \u001b[0mpredicts\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mmodel\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mimages\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     16\u001b[0m             \u001b[0mloss\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mF\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mcross_entropy\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mpredicts\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mlabels\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     17\u001b[0m             \u001b[0mavg_loss\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mpaddle\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmean\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mloss\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32m~\\Anaconda3\\lib\\site-packages\\paddle\\nn\\layer\\layers.py\u001b[0m in \u001b[0;36m__call__\u001b[1;34m(self, *inputs, **kwargs)\u001b[0m\n\u001b[0;32m   1252\u001b[0m         ):\n\u001b[0;32m   1253\u001b[0m             \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_build_once\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0minputs\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m-> 1254\u001b[1;33m             \u001b[1;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mforward\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0minputs\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m   1255\u001b[0m         \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m   1256\u001b[0m             \u001b[1;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_dygraph_call_func\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0minputs\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32m<ipython-input-3-628416c539ee>\u001b[0m in \u001b[0;36mforward\u001b[1;34m(self, inputs)\u001b[0m\n\u001b[0;32m      6\u001b[0m         \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mfc3\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mLinear\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0min_featuress\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m100\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mout_features\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m10\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      7\u001b[0m     \u001b[1;32mdef\u001b[0m \u001b[0mforward\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0minputs\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 8\u001b[1;33m         \u001b[0moutputs1\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mfc1\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0minputs\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      9\u001b[0m         \u001b[0moutputs1\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mF\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mReLU\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0moutputs1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     10\u001b[0m         \u001b[0moutputs2\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mfc2\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0moutputs1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32m~\\Anaconda3\\lib\\site-packages\\paddle\\nn\\layer\\layers.py\u001b[0m in \u001b[0;36m__getattr__\u001b[1;34m(self, name)\u001b[0m\n\u001b[0;32m   1472\u001b[0m                     \u001b[1;32mreturn\u001b[0m \u001b[0m_convert_into_variable\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0m_buffers\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mname\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m   1473\u001b[0m                 \u001b[1;32mreturn\u001b[0m \u001b[0m_buffers\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mname\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m-> 1474\u001b[1;33m         \u001b[1;32mreturn\u001b[0m \u001b[0mobject\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__getattribute__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mname\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m   1475\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m   1476\u001b[0m     \u001b[1;32mdef\u001b[0m \u001b[0m__setattr__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mname\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mvalue\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mAttributeError\u001b[0m: 'MNIST' object has no attribute 'fc1'"
     ]
    }
   ],
   "source": [
    "import paddle\n",
    "paddle.vision.set_image_backend('cv2')\n",
    "model=MNIST()\n",
    "def train(model):\n",
    "    model.train()\n",
    "    train_loader=paddle.io.DataLoader(paddle.vision.datasets.MNIST(mode='train'),\n",
    "                                     batch_size=16,\n",
    "                                     shuffle=True)\n",
    "    opt=paddle.optimizer.SGD(learning_rate=1e-2,parameters=model.parameters())\n",
    "    EPOCH_NUM=5\n",
    "    for epoch in range(EPOCH_NUM):\n",
    "        for batch_id,data in enumerate(train_loader()):\n",
    "            images=norm_img(data[0]).astype('float32')\n",
    "            labels=data[1].astype('int64')\n",
    "            predicts=model(images)\n",
    "            loss=F.cross_entropy(predicts,labels)\n",
    "            avg_loss=paddle.mean(loss)\n",
    "            if batch_id%1000==0:\n",
    "                print('epoch_id:{},loss is:{}'.format(epoch,batch_id,avg_loss.numpy()))\n",
    "            avg_loss.backward()\n",
    "            opt.step()\n",
    "            opt.clear_grad()\n",
    "train(model)\n",
    "paddle.save(model.state_dict(),'./mnist.pdparams')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "img_path='../Desktop/9.jpg'\n",
    "im = Image.open(img_path)\n",
    "plt.imshow(im)\n",
    "plt.show()\n",
    "im=im.convert('L')\n",
    "print('原始形状:',np.array(im).shape)\n",
    "im = im.resize((28,28),Image.ANTIALIAS)\n",
    "plt.imshow(im)\n",
    "plt.show()\n",
    "print('采样后图像形状:',np.array(im).shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_image(img_path):\n",
    "    im = Image.open(img_path.convert('L'))\n",
    "    im = im.resize((28,28),Image.ANTIALIAS)\n",
    "    im = np.array(im).reshape(1,-1).astype(np.float32)\n",
    "    im = 1 -im /255\n",
    "    return im\n",
    "model =MNIST()\n",
    "params_file_path='.data/mnist.pdparams'\n",
    "param_dict=paddle.load(params_file_path)\n",
    "model.load_dict(param_dict)\n",
    "model.eval()\n",
    "tensor_img=load_image(img_path)\n",
    "result=model(paddle.to_rensor_img)\n",
    "print('本次预测的数字是:',np.argsort(result.numpy())[0][-1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
